#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QVBoxLayout>
#include <QMessageBox>
#include <QFileInfo>
#include <QDir>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , currentIndex(-1)
{
    ui->setupUi(this);
    setupMediaPlayer();
    
    // 设置窗口标题
    setWindowTitle("媒体播放器");
    
    // 初始化进度定时器
    progressTimer = new QTimer(this);
    connect(progressTimer, &QTimer::timeout, this, &MainWindow::updateProgress);
    progressTimer->start(1000); // 每秒更新一次
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setupMediaPlayer()
{
    // 创建媒体播放器
    mediaPlayer = new QMediaPlayer(this);
    audioOutput = new QAudioOutput(this);
    videoWidget = new QVideoWidget(this);
    
    // 设置音频输出
    mediaPlayer->setAudioOutput(audioOutput);
    
    // 设置视频输出
    mediaPlayer->setVideoOutput(videoWidget);
    
    // 将视频控件添加到UI中
    QVBoxLayout *layout = new QVBoxLayout(ui->mediaWidget);
    layout->addWidget(videoWidget);
    layout->setContentsMargins(0, 0, 0, 0);
    
    // 连接信号和槽
    connect(mediaPlayer, &QMediaPlayer::durationChanged, this, &MainWindow::updateDuration);
    connect(mediaPlayer, &QMediaPlayer::positionChanged, this, &MainWindow::updatePosition);
    
    // 设置音频输出音量
    audioOutput->setVolume(50);
}

void MainWindow::on_pauseBtn_clicked()
{
    if (mediaPlayer->playbackState() == QMediaPlayer::PlayingState) {
        mediaPlayer->pause();
        ui->pauseBtn->setText("播放");
    } else {
        mediaPlayer->play();
        ui->pauseBtn->setText("暂停");
    }
}

void MainWindow::on_preBtn_clicked()
{
    if (mediaFiles.isEmpty()) return;
    
    if (currentIndex > 0) {
        currentIndex--;
    } else {
        currentIndex = mediaFiles.size() - 1;
    }
    
    loadMediaFile(mediaFiles[currentIndex]);
    mediaPlayer->play();
    ui->pauseBtn->setText("暂停");
}

void MainWindow::on_nextBtn_clicked()
{
    if (mediaFiles.isEmpty()) return;
    
    if (currentIndex < mediaFiles.size() - 1) {
        currentIndex++;
    } else {
        currentIndex = 0;
    }
    
    loadMediaFile(mediaFiles[currentIndex]);
    mediaPlayer->play();
    ui->pauseBtn->setText("暂停");
}

void MainWindow::on_listBtn_clicked()
{
    QStringList filters;
    filters << "音频文件 (*.mp3 *.wav *.flac *.aac *.ogg *.m4a)"
            << "视频文件 (*.mp4 *.avi *.mkv *.mov *.wmv *.flv *.webm)"
            << "所有文件 (*.*)";
    
    QStringList files = QFileDialog::getOpenFileNames(
        this,
        "选择媒体文件",
        QDir::homePath(),
        filters.join(";;")
    );
    
    if (!files.isEmpty()) {
        for (const QString &file : files) {
            if (!mediaFiles.contains(file)) {
                mediaFiles.append(file);
                QFileInfo fileInfo(file);
                ui->mediaListWidget->addItem(fileInfo.fileName());
            }
        }
        
        // 如果是第一个文件，自动播放
        if (currentIndex == -1 && !mediaFiles.isEmpty()) {
            currentIndex = 0;
            loadMediaFile(mediaFiles[0]);
            mediaPlayer->play();
            ui->pauseBtn->setText("暂停");
        }
    }
}

void MainWindow::on_mediaListWidget_itemDoubleClicked(QListWidgetItem *item)
{
    int index = ui->mediaListWidget->row(item);
    if (index >= 0 && index < mediaFiles.size()) {
        currentIndex = index;
        loadMediaFile(mediaFiles[currentIndex]);
        mediaPlayer->play();
        ui->pauseBtn->setText("暂停");
    }
}

void MainWindow::loadMediaFile(const QString &filePath)
{
    mediaPlayer->setSource(QUrl::fromLocalFile(filePath));
    
    // 更新窗口标题显示当前播放的文件名
    QFileInfo fileInfo(filePath);
    setWindowTitle(QString("媒体播放器 - %1").arg(fileInfo.fileName()));
    
    // 更新列表选中项
    if (currentIndex >= 0 && currentIndex < ui->mediaListWidget->count()) {
        ui->mediaListWidget->setCurrentRow(currentIndex);
    }
}

void MainWindow::updateProgress()
{
    if (mediaPlayer->playbackState() == QMediaPlayer::PlayingState) {
        qint64 position = mediaPlayer->position();
        qint64 duration = mediaPlayer->duration();
        updateTimeLabel(position, duration);
    }
}

void MainWindow::updateDuration(qint64 duration)
{
    ui->progressSlider->setMaximum(duration);
    updateTimeLabel(mediaPlayer->position(), duration);
}

void MainWindow::updatePosition(qint64 position)
{
    if (!ui->progressSlider->isSliderDown()) {
        ui->progressSlider->setValue(position);
    }
    updateTimeLabel(position, mediaPlayer->duration());
}

void MainWindow::on_progressSlider_sliderMoved(int position)
{
    mediaPlayer->setPosition(position);
}

void MainWindow::updateTimeLabel(qint64 position, qint64 duration)
{
    QString timeText = QString("%1 / %2")
        .arg(formatTime(position))
        .arg(formatTime(duration));
    ui->timeLabel->setText(timeText);
}

QString MainWindow::formatTime(qint64 ms)
{
    int seconds = ms / 1000;
    int minutes = seconds / 60;
    seconds = seconds % 60;
    return QString("%1:%2")
        .arg(minutes, 2, 10, QChar('0'))
        .arg(seconds, 2, 10, QChar('0'));
}

bool MainWindow::isVideoFile(const QString &filePath)
{
    QString extension = QFileInfo(filePath).suffix().toLower();
    QStringList videoExtensions = {"mp4", "avi", "mkv", "mov", "wmv", "flv", "webm"};
    return videoExtensions.contains(extension);
}
